package com.jwt.demo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.jwt.demo.config.RolePermission;
import com.jwt.demo.db.bean.UserLogin;
import com.jwt.demo.db.bean.UserMessage;
import com.jwt.demo.db.bean.UserRole;
import com.jwt.demo.db.mapper.UserLoginMapper;
import com.jwt.demo.db.mapper.UserMessageMapper;
import com.jwt.demo.db.mapper.UserRoleMapper;
import com.jwt.demo.model.TokenLoginInfo;
import com.jwt.demo.model.UserLoginModel;
import com.jwt.demo.service.UserLoginService;
import com.jwt.demo.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.beans.Transient;
import java.util.Date;
import java.util.List;

@Service
public class UserLoginServiceImpl implements UserLoginService {

    // 登录表
    @Autowired
    private UserLoginMapper userLoginMapper;

    // 个人信息
    @Autowired
    private UserMessageMapper userMessageMapper;

    // 账号访问权限
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 用户注册信息
     * @author chenlirun
     * @date 2021/7/8 15:14
     */
    @Override
    @Transient
    public JsonResult<?> insert(UserLoginModel userLoginModel){
        if (ObjectUtil.isEmpty(userLoginModel)){
            throw new BaseException(BaseCodeResult.ERROR,"提交的注册信息为空");
        }
        //输入手机号
        String phone = userLoginModel.getPhone();
        if(StringUtils.isBlank(phone)){
            throw new BaseException(BaseCodeResult.ERROR,"手机号不能为空");
        }
        // 加密密码
        String password = userLoginModel.getPassword();
        if(StringUtils.isBlank(password)){
            throw new BaseException(BaseCodeResult.ERROR,"请设置你的密码");
        }
        if(password.length()>18||password.length()<4){
            throw new BaseException(BaseCodeResult.ERROR,"密码长度在4-18");
        }
        String salt = RandomUtil.getSalt();
        String md5Encryption = PasswordUtil.getMD5Encryption(password, salt);
        // 账号生成规则
        UserLogin userLoginByNumber=null;
        Long number = 0L;
        do{
            number = RandomUtil.getNumber();
            userLoginByNumber = userLoginMapper.selectUserLoginByNumber(number);
        } while (userLoginByNumber != null);
        UserLogin userLogin = new UserLogin();
        userLogin.setSalt(salt);
        userLogin.setCreateTime(new Date());
        userLogin.setNumber(number);
        userLogin.setUsername("嘻哈少年"+number);
        userLogin.setPassword(md5Encryption);
        userLogin.setPhone(phone);
        int i = userLoginMapper.insertSelective(userLogin);
        if (i == 0){
            throw new BaseException(BaseCodeResult.ERROR,"用户信息注册失败");
        }
        UserLogin userLoginByNumber1 = userLoginMapper.selectUserLoginByNumber(number);
        if (ObjectUtil.isEmpty(userLoginByNumber1)){
            throw new BaseException(BaseCodeResult.ERROR,"该账号信息不存在");
        }
        Long id = userLoginByNumber1.getId();
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        userRole.setRoleId((byte) 5);
        int i1 = userRoleMapper.insertSelective(userRole);
        if(i1 == 0){
            int deleteUserLogin = userLoginMapper.deleteByPrimaryKey(id);
            if(deleteUserLogin == 0){
                throw new BaseException(BaseCodeResult.ERROR,"用户登录信息删除失败");
            }
            throw new BaseException(BaseCodeResult.ERROR,"用户权限信息注册失败");
        }

        return new JsonResult<>(BaseCodeResult.SUCCESS,"注册成功",userLogin);
    }

    @Override
    public JsonResult<String> login(UserLogin userLogin, HttpServletRequest request){

        if(ObjectUtil.isEmpty(userLogin)){
            throw new BaseException(BaseCodeResult.ERROR,"登录表单提交内容为空");
        }
        String phone = userLogin.getPhone();
        if(ObjectUtil.isEmpty(phone)){
            throw new BaseException(BaseCodeResult.ERROR,"账号为空");
        }
        String password = userLogin.getPassword();
        if(ObjectUtil.isEmpty(password)){
            throw new BaseException(BaseCodeResult.ERROR,"密码为空");
        }
        boolean b = RegexValidateUtil.checkMobilePhone(phone);
        String token = "";
        if(b){
            // 查询用户登录信息
            UserLogin userLogin2 = new UserLogin();
            userLogin2.setPhone(phone);
            UserLogin userLogin1 = userLoginMapper.selectUserLogin(userLogin2);
            String salt = userLogin1.getSalt();
            // 用户输入的密码加密
            String md5Encryption = PasswordUtil.getMD5Encryption(password, salt);
            // 数据库存储的密码
            String passwordData = userLogin1.getPassword();
            if(!md5Encryption.equals(passwordData)){
                throw new BaseException(BaseCodeResult.ERROR,"密码不正确");
            }
            Long id = userLogin1.getId();
            token = UserLoginTokenUtil.sign(id);
        }else {
            // 查询用户登录信息
            UserLogin userLogin2 = new UserLogin();
            userLogin2.setNumber(Long.valueOf(phone));
            UserLogin userLogin1 = userLoginMapper.selectUserLogin(userLogin2);
            String salt = userLogin1.getSalt();
            // 用户输入的密码加密
            String md5Encryption = PasswordUtil.getMD5Encryption(password, salt);
            // 数据库存储的密码
            String passwordData = userLogin1.getPassword();
            if(!md5Encryption.equals(passwordData)){
                throw new BaseException(BaseCodeResult.ERROR,"密码不正确");
            }
            // 获取用户的id
            Long id = userLogin1.getId();
            token = UserLoginTokenUtil.sign(id);
        }
        return new JsonResult<String>(BaseCodeResult.SUCCESS,"登录成功","",token);
    }

    /**
     * 查找个人用户信息
     * @author chenlirun
     * @date 2021/7/17 14:55
     */
    @Override
    @Transactional
    public JsonResult<List<UserLoginModel>> selectPersonal(HttpServletRequest request){
        //解析token
        Long tokenById = UserLoginTokenUtil.getTokenById(request);
        List<UserLoginModel> userLoginModels = userLoginMapper.selectUserLoginModel(tokenById);
        return new JsonResult<>(BaseCodeResult.SUCCESS,"",userLoginModels);
    }

}
